package com.sitech.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;

import com.sitech.pojo.UserBean;

public class LoginUtils {
	/**记住我功能*/
	public static void remeberMe(UserBean user,
			HttpServletRequest request, HttpServletResponse response) {
		System.out.println("------");
		//1:创建2个Cookie，存放指定值
		String name = "";
		try {
			name = URLEncoder.encode(user.getUsername(), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		Cookie nameCookie = new Cookie("name",name);
		Cookie passwordCookie = new Cookie("password",user.getPassword());
		//2:设置Cookie的有效路径（指定当前项目）
		nameCookie.setPath(request.getContextPath()+"/");
		passwordCookie.setPath(request.getContextPath()+"/");
		//3:设置Cookie的有效时间（1周）
		//获取页面复选框的值（用作判断）
		String remeberMe = user.getRemeberMe();
		//此时表示复选框选中
		if(remeberMe!=null && remeberMe.equals("yes")){
			nameCookie.setMaxAge(7*24*60*60);
			passwordCookie.setMaxAge(7*24*60*60);
		}
		//此时表示复选框没有被选中
		else{
			nameCookie.setMaxAge(0);
			passwordCookie.setMaxAge(0);
		}
		//4：将Cookie存放到response中
		response.addCookie(nameCookie);
		response.addCookie(passwordCookie);
	}

	
	/**在访问首页index.jsp页面之前，先从Cookie中获取name，password的值，并显示在页面上（完成记住我）*/
	public static void forwordIndexPage(ModelAndView md ,String path, HttpServletRequest request) {
		System.out.println(path);
		if(path!=null && path.equals("/login/startLogin.html")){
			String name = "";
			String password = "";
			String checked = "";
			Cookie [] cookies = request.getCookies();
			if(cookies!=null && cookies.length>0){
				for(Cookie cookie:cookies){
					if(cookie.getName().equals("name")){
						name = cookie.getValue();
						/**
						 * 如果name出现中文，对中文进行解码
						 */
						try {
							name = URLDecoder.decode(name, "UTF-8");
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						}
						checked = "checked";
					}
					if(cookie.getName().equals("password")){
						password = cookie.getValue();
					}
				}
			}
			System.out.println(name+password);
			md.addObject("username", name);
			md.addObject("password", password);
			md.addObject("remeberMe", checked);
		}
	}
}
